package com.zengde.ai_sandbox.controller;

import com.zengde.ai_sandbox.service.impl.MyDbModelService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
@RequiredArgsConstructor
public class MyDoubaoController {

    private final MyDbModelService doubaoService;

    /**
     * 豆包流式对话接口
     * @param sessionId 会话ID（用于多轮对话）
     * @param message 用户消息
     * @return SSE流式响应
     */
//    @GetMapping(value = "/chat", produces = "text/event-stream;charset=UTF-8")
    @GetMapping(value = "/chat", produces = "text/event-stream")
    public Flux<String> chat(
            @RequestParam String sessionId,
            @RequestParam String message) {



        return doubaoService.streamDoubaoResponse(sessionId, message)
                .map(content -> {
                    // 1. 确保内容只包含可打印字符
                    String cleanContent = content.replaceAll("[^\\x20-\\x7E]", "");

                    // 2. 正确格式化SSE事件
                    return "data: " + cleanContent + "\n\n";
                }); // SSE格式
    }

    /**
     * 重置对话历史
     * @param sessionId 会话ID
     */
    @GetMapping("/reset")
    public String resetConversation(@RequestParam String sessionId) {
        doubaoService.resetSession(sessionId);
        return "会话 " + sessionId + " 已重置";
    }
}